import axios from "axios";
import XParams from './XParams'
import Vue from 'vue'
import store from '../store/index'
import $ from 'jquery'
import xtoken from './xtoken'

//请求超时时间 5分钟
let timeout = 300000

// 创建axios实例
const axios4xurl = axios.create({
    // baseURL: dataUrl.DEV_DATA_URL, // api 的 base_url
    timeout: timeout
});

// request拦截器
axios4xurl.interceptors.request.use(
    config => {
        let headerParams =  xtoken.get();
        if (config.method === "post") {
            let contentType = config['Content-Type'];
            if (contentType && contentType.includes("/json")) {
                /*可以自己改变post传输类型*/
                headerParams = Object.assign(headerParams,
                    {"Content-Type": "application/json"});
            } else {
                headerParams = Object.assign(headerParams,
                    {"Content-Type": "application/x-www-form-urlencoded"});
                // post方法穿的data进行处理
                // config.data = qs.s tringify(config.data);
            }

        }
        config.headers = headerParams;
        return config;
    },
    error => {
        // Do something with request error
        console.log(error); // for debug
        Promise.reject(error);
    }
);

// response 拦截器
axios4xurl.interceptors.response.use(
    response => {
        /**
         * 具体状态根据后台接口定义,可以在此处统一处理请求失败和返回失败的情况
         */
        const res = response;
        return res;
    },
    error => {
        console.log("err" + error); // for debug
        // Message({
        //     message: error.message,
        //     type: "error",
        //     duration: 5 * 1000
        // });
        return Promise.reject(error);
    }
);

export default {
    /**
     *
     * 封装get方法,参数为url和请求参数对象，具体的返回的resolve根据后台确定,以下的其他请求方法参数类似也可以修改
     * @export
     * @param {*} url
     * @param {*} [params={}]
     * @returns
     */
    get(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAxiosParams(data);
        return new Promise((resolve) => {
            axios4xurl.get(url, {
                params: params
            }).then(response => {
                resolve(response.data);
            }).catch(err => {
                if (toError) {
                    window.location.href = "/error?msg=" + err.message
                } else {
                    console.log("get url:", url);
                    console.log("get params:", JSON.stringify(data));
                    console.log("get error:", err.message);
                }
            });
        });
    },
    getLoading(url, data = {}, toError = false) {
        let headerParams = xtoken.get() ;
        let params = XParams.convertAxiosParams(data);
        //设置开启加载动画
        store.state.loadingImg = true
        return new Promise((resolve) => {
            axios4xurl.get(url, {
                params: params
            }).then(response => {
                resolve(response.data);
                //设置关闭加载动画
                store.state.loadingImg = false
            }).catch(err => {
                if (toError) {
                    window.location.href = "/error?msg=" + err.message
                } else {
                    console.log("get url:", url);
                    console.log("get params:", JSON.stringify(data));
                    console.log("get error:", err.message);
                }
                //设置关闭加载动画
                store.state.loadingImg = false
            });
        });
    },
    getSync(url, data = {}, toError = false) {
        let headerParams = xtoken.get();
        let params = XParams.convertAjaxParams(data);
        return new Promise((resolve) => {
            $.ajax({
                url: url,
                type: "GET",
                dataType: "json",
                async: false,
                headers: headerParams,
                data: params,
                timeout: timeout,
                success: (response, textStatus, request) => {
                    resolve(response);
                },
                error: (err) => {
                    if (toError) {
                        Vue.$router.push({path: "/error?msg=" + err.responseText})
                    } else {
                        console.log("getSync error url:", url);
                        console.log("getSync error params:", JSON.stringify(params));
                        console.log("getSync error msg:", JSON.stringify(err));
                    }
                }
            });
        });
    },
    getSyncLoading(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAjaxParams(data);
        //设置开启加载动画
        store.state.loadingImg = true
        return new Promise((resolve) => {
            $.ajax({
                url: url,
                type: "GET",
                dataType: "json",
                async: false,
                headers: headerParams,
                data: params,
                timeout: timeout,
                success: (response, textStatus, request) => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    resolve(response);
                },
                error: (err) => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    if (toError) {
                        Vue.$router.push({path: "/error?msg=" + err.responseText})
                    } else {
                        console.log("getSync error url:", url);
                        console.log("getSync error params:", JSON.stringify(params));
                        console.log("getSync error msg:", JSON.stringify(err));
                    }
                }
            });
        });
    },
    /**
     *
     *封装post方法,参数为url 和请求参数对象，具体的返回的resolve根据后台确定
     * @export
     * @param {*} url
     * @param {*} [data={}]
     * @returns
     */
    postDataJson(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAjaxParams(data);
        return new Promise((resolve) => {
            axios4xurl.post(url, data, {"Content-Type": "application/json"}, {headers: {headerParams}}).then(
                response => {
                    resolve(response.data);
                },
                err => {
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        // console.log("post url:", url);
                        // console.log("post params:", JSON.stringify(data));
                        console.log("post error:", err.message);
                    }
                }
            );
        });
    },
    postDataJsonLoading(url, data = {}, toError = false) {
        //设置开启加载动画
        let headerParams =  xtoken.get();
        let params = XParams.convertAjaxParams(data);
        store.state.loadingImg = true;
        return new Promise((resolve) => {
            axios4xurl.post(url, data, {"Content-Type": "application/json"}, {headers: headerParams}).then(
                response => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    resolve(response.data);
                },
                err => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("post url:", url);
                        console.log("post params:", JSON.stringify(data));
                        console.log("post error:", err.message);
                    }
                }
            );
        });
    },
    post(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAxiosParams(data);
        return new Promise((resolve) => {
            axios4xurl.post(url, params, {headers: headerParams}).then(
                response => {
                    resolve(response.data);
                },
                err => {
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        // console.log("post url:", url);
                        // console.log("post params:", JSON.stringify(data));
                        console.log("post error:", err.message);
                    }
                }
            );
        });
    },
    postLoading(url, data = {}, toError = false) {
        let params = XParams.convertAxiosParams(data);
        let headerParams =  xtoken.get();
        console.log(" postLoading  : " + url + "data===>" + params);
        //设置开启加载动画
        store.state.loadingImg = true
        return new Promise((resolve) => {
            axios4xurl.post(url, params, {headers: headerParams}).then(
                response => {
                    resolve(response.data);
                    //设置关闭加载动画
                    store.state.loadingImg = false
                },
                err => {
                    if (toError) {
                        Vue.$router.push({path: "/error?msg=" + err.message})
                    } else {
                        // console.log("post url:", url);
                        // console.log("post params:", JSON.stringify(data));
                        console.log("post error:", err.message);
                    }
                    //设置关闭加载动画
                    store.state.loadingImg = false
                }
            );
        });
    },
    postSync(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAjaxParams(data);
        return new Promise((resolve) => {
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                async: false,
                headers: headerParams,
                data: params,
                timeout: timeout,
                success: (response, textStatus, request) => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    resolve(response);
                },
                error: (err) => {
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("postSync url:", url);
                        console.log("postSync params:", params);
                        console.log("postSync error:", JSON.stringify(err));
                    }
                }
            });
        });
    },
    postDataJsonLoadingSync(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAjaxParams(data);
        return new Promise((resolve) => {
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                async: false,
                headers: headerParams,
                data: JSON.stringify(params),
                contentType: 'application/json',
                timeout: timeout,
                success: async (response, textStatus, request) => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    await resolve(response);
                },
                error: (err) => {
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("postSync url:", url);
                        console.log("postSync params:", params);
                        console.log("postSync error:", JSON.stringify(err));
                    }
                }
            });
        });
    },
    postFileLoading(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        //设置开启加载动画
        store.state.loadingImg = true;
        return new Promise((resolve) => {
            $.ajax({
                url: url,
                type: 'POST',
                headers: headerParams,
                data: data,
                processData: false,         // 告诉jQuery不要去处理发送的数据
                contentType: false,        // 告诉jQuery不要去设置Content-Type请求头
                timeout: timeout,
                success: (response, textStatus, request) => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    resolve(response);
                },
                error: (err) => {
                    //设置关闭加载动画
                    store.state.loadingImg = false
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("postFile url:", url);
                        console.log("postFile error:", JSON.stringify(err));
                    }
                }
            })
        });
    },
    patch(url, data = {}, toError = false) {
        let params = XParams.convertAxiosParams(data);
        let headerParams =  xtoken.get();
        return new Promise((resolve) => {
            axios4xurl.patch(url, params, {headers: headerParams}).then(
                response => {
                    resolve(response.data);
                },
                err => {
                    if (toError) {
                        Vue.$router.push({path: "/error?msg=" + err.message})
                    } else {
                        console.log("patch url:", url);
                        console.log("patch params:", JSON.stringify(data));
                        console.log("patch error:", err.message);
                    }
                }
            );
        });
    },
    putLoading(url, data = {}, toError = false) {
        let params = XParams.convertAxiosParams(data);
        let headerParams =  xtoken.get();
        //设置开启加载动画
        store.state.loadingImg = true;
        return new Promise((resolve) => {
            axios4xurl.put(url, params, {headers: headerParams}).then(
                response => {
                    store.state.loadingImg = false;
                    resolve(response.data);
                },
                err => {
                    //设置关闭加载动画
                    store.state.loadingImg = false;
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("put url:", url);
                        console.log("put params:", JSON.stringify(data));
                        console.log("put error:", err.message);
                    }
                }
            );
        });
    },
    put(url, data = {}, toError = false) {
        let params = XParams.convertAxiosParams(data);
        let headerParams =  xtoken.get();
        return new Promise((resolve) => {
            axios4xurl.put(url, params, {headers: headerParams}).then(
                response => {
                    resolve(response.data);
                },
                err => {
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("put url:", url);
                        console.log("put params:", JSON.stringify(data));
                        console.log("put error:", err.message);
                    }
                }
            );
        });
    },
    putSync(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAjaxParams(data);
        return new Promise((resolve) => {
            $.ajax({
                url: url,
                type: "PUT",
                dataType: "json",
                async: false,
                headers: headerParams,
                data: params,
                timeout: timeout,
                success: (response, textStatus, request) => {
                    resolve(response);
                },
                error: (err) => {
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("putSync url:", url);
                        console.log("putSync params:", params);
                        console.log("putSync error:", JSON.stringify(err));
                    }
                }
            });
        });
    },
    delete(url, data = {}, toError = false) {
        let headerParams =  xtoken.get();
        let params = XParams.convertAxiosParams(data);
        return new Promise((resolve) => {
            axios4xurl.delete(url, params,{headers: headerParams}).then(
                response => {
                    resolve(response.data);
                },
                err => {
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("put url:", url);
                        console.log("put params:", JSON.stringify(data));
                        console.log("put error:", err.message);
                    }
                }
            );
        });
    },
    deleteLoading(url, data = {}, toError = false) {
        let params = XParams.convertAxiosParams(data);
        store.state.loadingImg = true;
        return new Promise((resolve) => {
            axios4xurl.delete(url, params).then(
                response => {
                    store.state.loadingImg = false;
                    resolve(response.data);
                },
                err => {
                    store.state.loadingImg = false;
                    if (toError) {
                        window.location.href = "/error?msg=" + err.message
                    } else {
                        console.log("put url:", url);
                        console.log("put params:", JSON.stringify(data));
                        console.log("put error:", err.message);
                    }
                }
            );
        });
    },
}
